package algorithm

import (
	"context"
	"fmt"
	"gluenet/pkg/agent"
	"gluenet/pkg/agent/option"
	"gluenet/pkg/agent/v2/rpc"
	"gluenet/pkg/nets"
	"os"
)

var CLI agent.Agent

func Install() error {
	url := os.Getenv("AGENT_NAT_URL")
	if url == "" {
		url = "nats://10.16.0.242:4222"
	}
	cli, err := agent.NewAgent(&rpc.Config{
		NatsUrl: url,
	})
	if err != nil {
		return err
	}
	CLI = cli

	return nil
}

func Simple(ctx context.Context, c nets.GlueNets, guid string, interGuid string, agentGuid string, ch chan float64) context.CancelFunc {
	CLI.Agent(agentGuid).Containers(guid).Update(option.ContainerOptions{
		CPUShares: 500,
	})
	CLI.Agent(agentGuid).Containers(interGuid).Update(option.ContainerOptions{
		CPUShares: 500,
	})

	ctx, cancel := context.WithCancel(ctx)
	for {
		select {
		case <-ctx.Done():
			return nil
		case m := <-ch:
			// todo 添加策略
			//req := define.UpdateContainerCpuRatiosReq{
			//	Guids:  []string{guid, interGuid},
			//	Ratios: []int{500, 500},
			//}
			//bts, _ := json.Marshal(req)
			//fmt.Printf("send agent %v\n",strings.Join([]string{agentGuid, v2.UpdateContainerCpuShare}, ":"))
			//if _, err := c.Request(strings.Join([]string{agentGuid, v2.UpdateContainerCpuShare}, ":"), bts); err != nil {
			//	fmt.Printf("\nrequest cpu share failed %v", err)
			//	continue
			//}

			CLI.Agent(agentGuid).Containers(guid).Update(option.ContainerOptions{
				CPUShares: 500,
			})
			CLI.Agent(agentGuid).Containers(interGuid).Update(option.ContainerOptions{
				CPUShares: 500,
			})

			fmt.Printf("instance %v cpu usage %v, inter guid %v, control agent guid %v\n", guid, interGuid, m, agentGuid)
		}
	}
	return cancel
}
